<template>
  <div class="body">
    <div class="home">
      <home-head/>
    </div>
    <AccessList @onCheckAll="onCheckAll" @onBookingClick="onBookingClick"/>
    <Auth v-if="!isAuth" @getUserInfo="init"/>
  </div>
</template>

<script>
  import HomeHead from '../../components/home/homeHead'
  import AccessList from '../../components/home/AccessList'
  import Auth from '../../components/base/Auth'
  import {getSetting, getUserInfo, setStorageSync, getStorageSync, getUserOpenId, showToast} from '../../api/wechat'
  import {register} from '../../api/index'

  export default {
    components: {
      AccessList,
      HomeHead,
      Auth
    },
    mounted () {
      this.init()
    },
    data () {
      return {
        isAuth: true
      }
    },
    methods: {
      onCheckAll () {
        console.log('all')
      },
      onBookingClick () {
        this.$router.push({
          path: '/pages/bookingForm/main'
        })
      },
      onAllListClick () {
        this.$router.push({
          path: '/pages/allList/main'
        })
      },
      getSetting () {
        getSetting(
          'userInfo',
          () => {
            console.log('y')
            this.isAuth = true
            showToast('正在登录')
            this.getUserInfo()
          }, () => {
            console.log('n')
            this.isAuth = false
          })
      },
      getUserInfo (e) {
        const onOpenIdComplete = (openId, userInfo) => {
          register(openId, userInfo)
          console.log('注册用户信息！')
        }
        getUserInfo(
          (userInfo) => {
            debugger
            setStorageSync('userInfo', userInfo)
            const openId = getStorageSync('openId')
            if (!openId || openId.length === 0) {
              getUserOpenId(openId => onOpenIdComplete(openId, userInfo))
            } else {
              console.log('onOpenIdComplete')
              onOpenIdComplete(openId, userInfo)
            }
          },
          () => {
            console.log('failed')
          }
        )
      },
      init () {
        // this.onBookingClick()
        this.getSetting()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .body {
    background: #ffffff;
  }
</style>
